package com.hspedu.seckill.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hspedu.seckill.mapper.UserMapper;
import com.hspedu.seckill.pojo.User;
import com.hspedu.seckill.service.UserService;
import com.hspedu.seckill.util.CookieUtil;
import com.hspedu.seckill.util.MD5Util;
import com.hspedu.seckill.util.UUIDUtil;
import com.hspedu.seckill.util.ValidatorUtil;
import com.hspedu.seckill.vo.LoginVo;
import com.hspedu.seckill.vo.RespBean;
import com.hspedu.seckill.vo.RespBeanEnum;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 验证用户登录信息
     */
    @Override
    public RespBean doLogin(HttpServletRequest request, HttpServletResponse response, LoginVo loginVo) {
        //获取请求的手机号和密码
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();

        //如果手机号或密码为空
        if (!StringUtils.hasText(mobile) || !StringUtils.hasText(password)) {
            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }

        //如果手机号格式不正确
        if (!ValidatorUtil.isMobile(mobile)) {
            return RespBean.error(RespBeanEnum.MOBILE_ERROR);
        }

        User user = userMapper.selectById(mobile);

        //如果手机号不存在
        if (null == user) {
            return RespBean.error(RespBeanEnum.MOBILE_NOT_EXIST);
        }

        String dbPass = MD5Util.midPassToDBPass(password, user.getSlat());

        //如果密码错误
        if (!dbPass.equals(user.getPassword())) {
            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }

        //获取用户票据设置cookie保存到浏览器
        String ticket = UUIDUtil.uuid();
        CookieUtil.setCookie(request, response, "userTicket", ticket);

        //将user信息存放在redis，实现分布式session
        redisTemplate.opsForValue().set("userTicket:" + ticket, user);


        return RespBean.success(ticket);
    }

    /**
     * 根据Cookie-ticket 获取用户的信息
     */
    @Override
    public User getUserByCookie(HttpServletRequest request,HttpServletResponse response) {
        String userTicket = CookieUtil.getCookieValue(request,"userTicket");

        if (!StringUtils.hasText(userTicket)){
            return null;
        }

        User user = (User) redisTemplate.opsForValue().get("userTicket:" + userTicket);
        if (null != user){
            //如果取出user不为空，就刷新cookie
            CookieUtil.setCookie(request, response, "userTicket", userTicket);
        }

        return user;
    }
}
